<!DOCTYPE html>
<html>
<head>
    <title>鹿鹿泽会员运动打卡日历</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
</head>
<body style="background-color: rgb(254, 254, 255);">
    {% include 'show_ins_info.html' %}
    <hr>
    <h2>鹿鹿泽会员运动打卡日历</h2>    

    <div class="form-row">
        <h4 style="width:60px;font-size:14px;">会员姓名</h4>
        <input id="cusNameInput" style="width:100px;" oninput="handleInput();">
    </div>
    <div id="cusNameList"></div>
    <div class="form-row" style="font-size:14px;">
        <h4 style="width:60px;">时间段</h4>
        <select id="interval" onchange="showChart('getName', this.value)">
            <option value="30">近30天</option>
            <option value="60">近60天</option>
            <option value="90">近90天</option>
            <option value="this_month">本月</option>
            <option value="this_year">今年</option>
        </select>
    </div>   
    <hr style="border-top:1px dashed;">
    <div id="txtBox" style="display: none;">
        <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
            <div id="title" style="color:rgb(95, 93, 87);font-size:18px;margin-top:20px;font-weight: bold;"></div>
            <div id="txt" style="color:#d4ad41;font-size:12px;margin-top:12px;"></div>
        </div>
    </div>
    <div id="sportChart" style="width: 100%;"></div>
    
    <div style="display: flex;flex-direction: row;justify-content: center;margin-bottom: 30px;"><div id='logo' style='color:#bfbcb6;font-size:12px;display: none;'>— 鹿鹿泽健身工作室 —</div></div>

    <script src="../static/js/common.js"></script>
    <script src="../static/js/echarts.min.js"></script>
    
    <script>
        let insName;
        let insId;
        let insRole;
        let insList;
        let cus_list;
        let myChart;

        document.addEventListener('DOMContentLoaded', function() {
            // loginCheck();        
            const insInfo = hideInsSelectBlockAndGetInsInfo();
            insId = insInfo.sessionInsId;
            insName = insInfo.sessionInsName;
            insRole = insInfo.sessionInsRole;
       

            fetch('/get_cus_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                cus_list = data;
            })
            .catch(error => console.error('Error:', error)); 
        });

        function showChart(getName, interval) {
            const txtBox=document.getElementById('txtBox');
            const logo=document.getElementById('logo');
            const sportChart = document.getElementById('sportChart');
            sportChart.innerHTML = '';

            try{
                myChart.dispose();
            }catch(error){
                
            }

            let startDate;
            let endDate;
            if (interval === 'this_year') {
                const today = new Date();
                startDate = new Date(today.getFullYear() + '-01-01');
                endDate = new Date();             
            }else if(interval === 'this_month'){
                const today = new Date();                
                startDate = new Date(today.getFullYear() + '-'+(today.getMonth()+1)+'-01');
                endDate = new Date();   
            }
            else {
                startDate = new Date();
                startDate.setDate(startDate.getDate() - interval+1);
                endDate = new Date();
            }

            let cusIdName;
            if (getName === 'getName') {
                cusIdName = document.getElementById('cusNameInput').value;
            } else {
                cusIdName = getName;
            }

            fetch('/get_train_calendar', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({'cusIdName': cusIdName, 'interval': interval})
            })
            .then(response => response.json())
            .then(data => {
                if (data['res'] === 'ok') {
                    console.log('train data:',data) 
                    const sex = data['data'][0][1];
                    // 统计每天的训练次数和内容
                    const dateCounts = {};
                    data['data'].forEach(item => {
                        const dateStr = dateToStringGmt(item[3], 'date');
                        if (!dateCounts[dateStr]) {
                            dateCounts[dateStr] = {
                                count: 1,
                                content: item[4]
                            };
                        } else {
                            dateCounts[dateStr].count++;
                        }
                    });
             
                    const result = [];
                    let currentDate = new Date(startDate);
                    while (currentDate <= endDate) {
                        const dateStr = toBeijingTimeString(currentDate);
                        const dateData = dateCounts[dateStr];
                        const isSpot = !!dateData;
                        let content = isSpot ? dateData.content : ':-o';
                        if (isSpot && dateData.count >= 2) {
                            content += ` × ${dateData.count}`;
                        }
                        result.push([dateStr, isSpot ? 1 : 0, content]);
                        currentDate.setDate(currentDate.getDate() + 1);
                    }
                    // console.log(result);
                    calendarSpot(result, startDate, endDate, sex);
                    logo.style.display='flex';
                    txtBox.style.display='flex';
                    txtBox.classList.add('calendar-txt');
                } else {
                    sportChart.innerHTML = '没有打卡记录';
                    logo.style.display='none';
                    // txtBox.sytle.display='none';
                }
            })
            .catch(error => {
                console.error('获取既往上课错误：', error);
            });
        }

        function calendarSpot(data, startDate, endDate, sex) {
            // console.log(data)
            const txtBox=document.getElementById('txtBox');
            const title=document.getElementById('title');
            const txt=document.getElementById('txt');
            title.innerHTML='';
            txt.innerHTML='';
            const cusName = document.getElementById('cusNameInput').value.slice(7);
            const interval = document.getElementById('interval').value;
            let titleStr;
            let gap;
            switch (interval) {
                case '30':
                    titleStr = `${cusName}${sex === '男' ? '先生' : '女士'}最近30天运动打卡记录`;
                    gap=120;
                    break;
                case '60':
                    titleStr = `${cusName}${sex === '男' ? '先生' : '女士'}最近60天运动打卡记录`;
                    gap=120;
                    break;
                case '90':
                    titleStr = `${cusName}${sex === '男' ? '先生' : '女士'}最近90天运动打卡记录`;
                    gap=120;
                    break;
                case 'this_month':
                    titleStr = `${cusName}${sex === '男' ? '先生' : '女士'}${startDate.getMonth()+1}月运动打卡记录`;
                    gap=120;
                    break;
                case 'this_year':
                    titleStr = `${cusName}${sex === '男' ? '先生' : '女士'}${startDate.getFullYear()}年运动打卡记录`;
                    gap=120;
                    break;
            }

            let daysCount=0;
            data.forEach(item=>{                
                if(parseInt(item[1])===1){
                    daysCount+=1;
                }
            });

            title.innerHTML=`${titleStr}`;
            txt.innerHTML=`运动打卡${daysCount}天`;


            const mainContainer = document.getElementById('sportChart');
            const containerWidth = mainContainer.offsetWidth;
            
            const numDays = 7;
            let numWeeks;
            if(interval==='this_year'){
                // numWeeks=52
                const oneDay = 24 * 60 * 60 * 1000;
                const diffDays = Math.round(Math.abs((endDate - startDate) / oneDay));
                numWeeks = Math.ceil(diffDays / 7);
            }else{
                const oneDay = 24 * 60 * 60 * 1000;
                const diffDays = Math.round(Math.abs((endDate - startDate) / oneDay));
                numWeeks = Math.ceil(diffDays / 7);
            }            

            const cellSize = Math.floor(containerWidth / numDays);
            mainContainer.style.height = (cellSize*0.8 * numWeeks)+gap + 'px';

            // console.log(numWeeks,cellSize,mainContainer.style.height)

            const processedData = data.map(item => [item[0], item[1]]);

            myChart = echarts.init(mainContainer);
            // startDate.setDate(startDate.getDate()+1);
            const option = {
                title: {
                    show:false,
                    top: 0,
                    left: 'center',
                    text: titleStr
                },
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        const originalItem = data.find(item => item[0] === params.data[0]);
                        return originalItem ? originalItem[2] : '';
                    }
                },
                visualMap: {
                    show: false,
                    min: 0,
                    max: 1,
                    type: 'piecewise',
                    orient: 'horizontal',
                    left: 'center',
                    top: 65,
                    inRange: {
                        color: ['#fcfaf2', '#f5c647']
                    }
                },
                calendar: {
                    orient: 'vertical',
                    top: 40,
                    left: 50,
                    right: 20,
                    cellSize: [cellSize, cellSize*0.8],
                    range: [toBeijingTimeString(startDate), toBeijingTimeString(endDate)],
                    itemStyle: {
                        borderWidth: 0.5
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: '#ccc',
                            type: 'solid'
                        }
                    },
                    dayLabel: {
                        firstDay: 1,
                        nameMap: 'cn',
                        margin:8,
                        fontSize: 13,
                        color:'#7d7972'
                    },
                    monthLabel: {
                        show: true,
                        nameMap: 'cn',
                        margin: 15,
                        fontSize: 16,
                        color:'#7d7972'
                    },
                    yearLabel: {
                        show: false
                    }
                },
                series: {
                    type: 'heatmap',
                    coordinateSystem: 'calendar',
                    data: processedData,
                    label: {
                        show: true,
                        formatter: function(p) {
                            return echarts.format.formatTime('d', p.data[0]);
                        },
                        textStyle: {
                            color: '#555555'
                        }
                    }
                }
            };

            myChart.setOption(option);
        }

        function handleInput() {
            const txtBox=document.getElementById('txtBox');
            txtBox.style.display='none';
            const logo=document.getElementById('logo');
            logo.style.display='none';
            const sportChart = document.getElementById('sportChart');
            sportChart.innerHTML = '';
            try{
                myChart.dispose();
            }catch(error){
                
            }

            const interval = document.getElementById('interval').value;
            const searchTerm = document.getElementById("cusNameInput").value.trim().toUpperCase();
            const resultList = document.getElementById("cusNameList");
            resultList.innerHTML = "";

            if (searchTerm === "") {
                resultList.style.display = "none";
                return;
            } else {
                resultList.style.display = "block";
                resultList.classList.add('cus-list-result-show');
                resultList.style.left = '206px';
                resultList.style.top = '138px';
            }

            cus_list.reverse().forEach(function(name) {
                if (name.includes(searchTerm)) {
                    const listItem = document.createElement("li");
                    listItem.textContent = name;
                    listItem.addEventListener("click", function() {
                        document.getElementById('cusNameInput').value = name;
                        resultList.style.display = "none";
                        showChart(name, interval);
                        resultList.innerHTML = "";
                    });
                    resultList.appendChild(listItem);
                }
            });
        }
    </script>
</body>
</html>
